//
//  shopDetailsViewController.m
//  lmq
//
//  Created by 千翼网络科技 on 2017/4/5.
//  Copyright © 2017年 yuanxin. All rights reserved.
//

#import "shopDetailsViewController.h"
#import "shopDetailsTableViewCell.h"
#import "configddd.h"
#import <Masonry/Masonry.h>
#import "UIImageView+WebCache.h"
#import <MJRefresh/MJRefresh.h>
#import "submitOrderViewController.h"
#import "loginViewController.h"

@interface shopDetailsViewController ()

@end

@implementation shopDetailsViewController

- (void)viewWillAppear:(BOOL)animated{
    
    _detailsTableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreTopic)];
    [_detailsTableView.mj_footer endRefreshing];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    size.height = 100;
    size.width = 100;
    picArr = [[NSMutableArray alloc]init];
    
    self.title = @"商品详情";
    self.view.backgroundColor = getColor(@"ffffff");
    footViewHeight = screenScale(66);
    
    [self initView];
    [self requestData];
    
    self.detailsTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, DEF_SCREEN_WIDTH, DEF_SCREEN_HEIGHT-64-screenScale(82)) style:UITableViewStyleGrouped];
}

#pragma mark ------------------------------ init

- (void)setDetailsTableView:(UITableView *)detailsTableView{
    
    _detailsTableView = detailsTableView;
    _detailsTableView.backgroundColor = getColor(@"f4f4f4");
    _detailsTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    _detailsTableView.separatorStyle = UITableViewCellSelectionStyleNone;
    _detailsTableView.delegate = self;
    _detailsTableView.dataSource = self;
    [self.view addSubview:_detailsTableView];
}

- (void)initView{
    
    //底部view
    
    UIView *bottomView=[[UIView alloc]init];
    [self.view addSubview:bottomView];
    [bottomView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.mas_equalTo(self.view).with.offset(0);
        make.left.mas_equalTo(self.view).with.offset(0);
        make.width.mas_equalTo(scrWidth());
        make.height.mas_equalTo(screenScale(80));
    }];
    
    //thread
    UIView *threadView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, scrWidth(), screenScale(1))];
    threadView.backgroundColor = [UIColor grayColor];
    [bottomView addSubview:threadView];
    
    //购买
    UIButton *gwdButton=[[UIButton alloc]initWithFrame:CGRectMake(DEF_SCREEN_WIDTH/2, 0, DEF_SCREEN_WIDTH / 2, screenScale(80))];
    gwdButton.titleLabel.font = get4sFont(14);
    [gwdButton setTitle:@"购买" forState:UIControlStateNormal];
    [gwdButton addTarget:self action:@selector(gwdButtonClick) forControlEvents:UIControlEventTouchUpInside];
    gwdButton.backgroundColor=[ZJCModel colorWithString:@"222222"];
    [bottomView addSubview:gwdButton];
    
    //现价
    nowPriceLable = [[UILabel alloc]init];
    nowPriceLable.textColor = getColor(@"252525");
    nowPriceLable.font = get4sFont(11);
    nowPriceLable.textAlignment = NSTextAlignmentCenter;
    [self.view addSubview:nowPriceLable];
    [nowPriceLable mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.mas_equalTo(self.view).with.offset(0);
        make.left.mas_equalTo(self.view).with.offset(0);
        make.width.mas_equalTo(scrWidth()/2/2);
        make.height.mas_equalTo(screenScale(80));
    }];
    
    //原价
    beforePriceLable = [[UILabel alloc]init];
    beforePriceLable.textColor = getColor(@"252525");
    beforePriceLable.font = get4sFont(11);
    beforePriceLable.textAlignment = NSTextAlignmentCenter;
    [self.view addSubview:beforePriceLable];
    [beforePriceLable mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.mas_equalTo(self.view).with.offset(0);
        make.left.mas_equalTo(self.view).with.offset(scrWidth()/2/2);
        make.width.mas_equalTo(scrWidth()/2/2);
        make.height.mas_equalTo(screenScale(80));
    }];
}

#pragma mark ------------------------------ click

- (void)gwdButtonClick{
    
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:[[UIApplication sharedApplication]keyWindow] animated:YES];
    hud.tag = 500;
    //提示文本
    hud.labelText = @"正在加载...";
    //是否有遮罩
    hud.dimBackground = YES;
    
    NSMutableDictionary *productParams=[[NSMutableDictionary alloc]init];
    [productParams setValue: [PublicFunction getConfigWithKey:@"token"] forKey:@"token"];
    
    [[MNetworkHandler sharedInstance]conURL:Is_Login
                                networkType:NetWorkPOST
                                     params:productParams
                                   delegate:nil
                                    showHUD:NO
                               successBlock:^(id returnData) {
                                   if ([[returnData objectForKey:@"code"]intValue]==1) {
                                       
                                       submitOrderViewController *submitOrderVC = [[submitOrderViewController alloc]init];
                                       submitOrderVC.shop_id = dataDic[@"goods_id"];
                                       [self.navigationController pushViewController:submitOrderVC animated:YES];
                                       [hud removeFromSuperview];
                                   }else{
                                       
                                       [hud removeFromSuperview];
                                       loginViewController *loginVc =[[loginViewController alloc]init];
                                       [self.navigationController presentViewController:loginVc animated:YES completion:^{}];
                                   }
                               } failureBlock:^(NSError *error) {
                                   
                                   [hud removeFromSuperview];
                                   NSLog(@"%@",error);
                                   [PublicFunction showAlert:nil message:@"没有连接网络" duration:10.0f];
                               }];
}

#pragma mark ------------------------------ requestData

- (void)requestData{
    
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:[[UIApplication sharedApplication]keyWindow] animated:YES];
    hud.tag = 500;
    //提示文本
    hud.labelText = @"正在加载...";
    //是否有遮罩
    hud.dimBackground = YES;
    
    NSMutableDictionary *productParams=[[NSMutableDictionary alloc]init];
    [productParams setValue: _partnerId forKey:@"id"];
    
    [[MNetworkHandler sharedInstance]conURL:Goods_Details
                                networkType:NetWorkPOST
                                     params:productParams
                                   delegate:nil
                                    showHUD:NO
                               successBlock:^(id returnData) {
                                   if ([[returnData objectForKey:@"code"]intValue]==1) {
                                       
                                       dataDic = [returnData objectForKey:@"data"];
                                       [_detailsTableView reloadData];
                                       
                                       nowPriceLable.text = [@"¥" stringByAppendingString:dataDic[@"goods_price"]];
                                       NSDictionary *attribtDic = @{NSStrikethroughStyleAttributeName: [NSNumber numberWithInteger:NSUnderlineStyleSingle]};
                                       NSMutableAttributedString *attribtStr = [[NSMutableAttributedString alloc]initWithString:[@"¥" stringByAppendingString:dataDic[@"goods_original_price"]] attributes:attribtDic];
                                       beforePriceLable.attributedText = attribtStr;
                                       
                                       NSLog(@"==\n\n\n==dataDic====%@",dataDic);
                                       
                                       [hud removeFromSuperview];
                                   }
                                   else if ([[returnData objectForKey:@"code"]intValue]==-1){
                                       
                                       [hud removeFromSuperview];
                                       [PublicFunction showAlert:nil message:[returnData objectForKey:@"msg"] duration:5.0f];
                                       
                                   }
                                   else{
                                       
                                       [hud removeFromSuperview];
                                       [_detailsTableView reloadData];
                                   }
                               } failureBlock:^(NSError *error) {
                                   
                                   [hud removeFromSuperview];
                                   NSLog(@"%@",error);
                                   [PublicFunction showAlert:nil message:@"没有连接网络" duration:10.0f];
                               }];
}

#pragma mark --------------------------- UITableViewDelegate

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{

    return screenScale(390);
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{

    return screenScale(560);
}

- (nullable UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{

    UIView *headView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, scrWidth(), screenScale(560))];
    
    //轮播
    NSMutableArray *picArray = [[NSMutableArray alloc]init];
    for (int i = 0 ; i < [dataDic[@"banner"] count] ; i ++) {
        
        NSString *str = dataDic[@"banner"][i][@"pic"];
        NSString *urlN = manage(AP_HOST, str);
        NSString *strUrl = [urlN stringByReplacingOccurrencesOfString:@"\\" withString:@"/"];
        [picArray addObject:strUrl];
    }
    
    [self.cycleScrollView setLocalizationImageNamesGroup:picArray];
    
    self.cycleScrollView = [SDCycleScrollView cycleScrollViewWithFrame:CGRectMake(0, 0, scrWidth(), screenScale(560)) imageNamesGroup:picArray];
    self.cycleScrollView.backgroundColor = [UIColor whiteColor];
    self.cycleScrollView.autoScroll = YES;
    self.cycleScrollView.pageControlAliment = SDCycleScrollViewPageContolAlimentCenter;
    self.cycleScrollView.delegate = self;
    self.cycleScrollView.pageDotColor = [UIColor grayColor]; // 自定义分页控件小圆标颜色
    self.cycleScrollView.currentPageDotImage = [UIImage imageNamed:@"hei"];
    self.cycleScrollView.pageDotImage = [UIImage imageNamed:@"hui"];
    self.cycleScrollView.placeholderImage = [UIImage imageNamed:@""];
    [headView addSubview:self.cycleScrollView];
    
    return headView;
}

- (nullable UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
        
        footerView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, scrWidth(), screenScale(66))];
        footerView.backgroundColor = getColor(@"f5f5f5");
    
        //刷新之后
        footerView2 = [[UIView alloc]initWithFrame:CGRectMake(0, screenScale(10), scrWidth(), footViewHeight)];
        footerView2.hidden = !hidden;
        [footerView addSubview:footerView2];
        
        for (int i = 0; i < [dataDic[@"details"] count]; i ++) {
            
            int height = 0;
            
            if (picArr.count > 0) {
                
                for (int j = 0 ; j < i ; j ++) {
                    
                    height += [picArr[j] intValue];
                }
                
                UIImageView *img = [[UIImageView alloc]initWithFrame:CGRectMake(0,height, scrWidth(), [picArr[i] intValue])];
                [footerView2 addSubview:img];
                
                NSString *urlWare = [dataDic[@"details"][i] objectForKey:@"pic"];
                NSString *urlN = manage(AP_HOST, urlWare);
                NSString *strUrl = [urlN stringByReplacingOccurrencesOfString:@"\\" withString:@"/"];
                NSURL *urlW = [NSURL URLWithString:strUrl];
                [img sd_setImageWithURL:urlW placeholderImage:[UIImage imageNamed:@"niunai"]];
            }
        }
        
        //上拉刷新文字提示
        footerView1 = [[UIView alloc]initWithFrame:CGRectMake(0, 0, scrWidth(), screenScale(66))];
        footerView1.backgroundColor = getColor(@"f5f5f5");
        footerView1.hidden = hidden;
        [footerView addSubview:footerView1];
        
        UIView *threadView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, scrWidth(), screenScale(1))];
        threadView.backgroundColor = getColor(@"dfdfdf");
        [footerView1 addSubview:threadView];
        
        UILabel *footLable = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, scrWidth(), screenScale(66))];
        footLable.text = @"继续拖动，查看图文详情";
        footLable.font = get4sFont(11);
        footLable.textAlignment = NSTextAlignmentCenter;
        [footerView1 addSubview:footLable];
        
        return footerView;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    
    return footViewHeight + screenScale(10);
}

#pragma mark ------------------------------- UITableViewDataSource

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    [tableView deselectRowAtIndexPath:indexPath animated:NO];//选中后的反显颜色即刻消失
    
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    [tableView registerClass:[shopDetailsTableViewCell class] forCellReuseIdentifier:@"identifier"];
    shopDetailsTableViewCell *cell = (shopDetailsTableViewCell *)[tableView dequeueReusableCellWithIdentifier:@"identifier" forIndexPath:indexPath];
    
    cell.dataDic = dataDic;
    cell.nameLable.text = dataDic[@"goods_name"];
    
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    if (dataDic) {
        
        cell.priceLable.text = [@"¥" stringByAppendingString:dataDic[@"goods_price"]];
        
        NSDictionary *attribtDic = @{NSStrikethroughStyleAttributeName: [NSNumber numberWithInteger:NSUnderlineStyleSingle]};
        NSMutableAttributedString *attribtStr = [[NSMutableAttributedString alloc]initWithString:[@"¥" stringByAppendingString:dataDic[@"goods_original_price"]] attributes:attribtDic];
        
        cell.beforePriceLable.attributedText = attribtStr;
    }
    
    NSString *urlGood = [dataDic objectForKey:@"shop_logo"];
    NSString *urlN = manage(AP_HOST, urlGood);
    NSString *strUrl = [urlN stringByReplacingOccurrencesOfString:@"\\" withString:@"/"];
    NSURL *urlW = [NSURL URLWithString:strUrl];
    [cell.logoImg sd_setImageWithURL:urlW placeholderImage:[UIImage imageNamed:@"niunai"]];
    
//    cell.textLab.text = dataDic[@"shop_content"];
    cell.text.text = dataDic[@"shop_content"];
    
    return cell;
}

- (void)loadMoreTopic{
    
    dispatch_async(dispatch_get_main_queue(), ^{
        
        
    });
    
    //1.获得全局的并发队列
//    dispatch_queue_t queue =  dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    //2.添加任务到队列中，就可以执行任务
    //异步函数：具备开启新线程的能力
//    dispatch_async(queue, ^{
    
        picArr = [[NSMutableArray alloc]init];
        NSMutableArray *arr = [[NSMutableArray alloc]init];
        footViewHeight = 0;
        
        for (int i = 0 ; i < [dataDic[@"details"] count]; i ++) {
            
            NSString *urlGood = dataDic[@"details"][i][@"pic"];
            NSString *urlN = manage(AP_HOST, urlGood);
            NSString *strUrl = [urlN stringByReplacingOccurrencesOfString:@"\\" withString:@"/"];
            
            NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:strUrl]];
            UIImage *image = [UIImage imageWithData:data];
            size = image.size;
            
            footViewHeight += size.height/(size.width/scrWidth());
            [arr insertObject:[NSString stringWithFormat:@"%f",size.height/(size.width/scrWidth())] atIndex:i];
        }
        
        [_detailsTableView.mj_footer endRefreshing];
        
        if ([dataDic[@"details"] count] > 0) {
            
            hidden = YES;
        }else{
            
            hidden = NO;
        }
        
        picArr = arr;
        NSLog(@"%@",picArr);
        [_detailsTableView reloadData];
//    });
    
    
    
}



@end
